package com.mantru.iotpot.Cook;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.viewpager2.widget.ViewPager2;

import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.mantru.iotpot.ApplicationClass;
import com.mantru.iotpot.Cleaning.CleanWayActivity;
import com.mantru.iotpot.Cook.adapter.ViewPagerAdapter;
import com.mantru.iotpot.Cook.fragment.CustomBottomSheetDialogFragment;
import com.mantru.iotpot.Cook.fragment.FirePowerFragmrnt;
import com.mantru.iotpot.Cook.fragment.SetTasteFragment;
import com.mantru.iotpot.DateClass.FirePowerDate;
import com.mantru.iotpot.DateClass.TasteData;
import com.mantru.iotpot.DateClass.TasteItem;
import com.mantru.iotpot.R;
import com.mantru.iotpot.Tools.LoadingDialogUtil;
import com.mantru.iotpot.Util.ToastUtils;
import com.mantru.iotpot.eventbus.FoodEvent;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

public class AdjustFoodActivity extends AppCompatActivity implements View.OnClickListener, FirePowerFragmrnt.OnDataPassListener , SetTasteFragment.OnDataPassListener{
    private int sid;
    private int vegetableId;
    private String weight = "";
    private String vegetableName = "";
    private LinearLayout back;
    private TextView name;
    private TabLayout tablLayout;
    private ViewPager2 viewPager;
    private Button save;
    private Button cook;
    private JSONObject savedJsonResult = new JSONObject();// 保存转换后的火力的JSONObject
    private JSONObject savedTasteJsonResult = new JSONObject();
    private String copiesQty = "";
    private ApplicationClass ac;
    private int select = 1;//1为保存菜谱，2为立即烹饪

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_adjust_food);
        ac = (ApplicationClass) getApplication();// 初始化 ApplicationClass
        sid = Integer.parseInt(getIntent().getStringExtra("sid"));//获取规格id
        vegetableId = Integer.parseInt(getIntent().getStringExtra("vegetableId"));//获取蔬菜id
        vegetableName = getIntent().getStringExtra("foodname");//获取蔬菜名
        weight = getIntent().getStringExtra("weight");//获取重量
        copiesQty = getIntent().getStringExtra("copiesQty");
        Log.d("AdjustFood","sid: " + sid + " vegetableId: " + vegetableId + " vegetableName: " + vegetableName + " copiesQty: " + copiesQty + " weight: " + weight);
        initialization();//初始化控件
        EventBus.getDefault().postSticky(new FoodEvent(sid, vegetableId));
    }

    //初始化控件
    private void initialization() {
        // 初始化控件
        back = findViewById(R.id.adjust_food_back);
        name = findViewById(R.id.adjust_food_name);
        tablLayout = findViewById(R.id.adjust_food_tabLayout);
        viewPager = findViewById(R.id.adjust_food_viewPager);
        save = findViewById(R.id.adjust_food_button1);
        cook = findViewById(R.id.adjust_food_button2);
        back.setOnClickListener(this);
        save.setOnClickListener(this);
        cook.setOnClickListener(this);
        name.setText(vegetableName + " " + copiesQty + "份 " + weight + "g");
        ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(this);
        viewPager.setAdapter(viewPagerAdapter);
        // 禁用 ViewPager2 的滑动效果
        viewPager.setUserInputEnabled(false);
        // 禁用 ViewPager2 的页面切换动画
        viewPager.setPageTransformer(null);
        // 绑定 TabLayout 和 ViewPager2
        new TabLayoutMediator(tablLayout, viewPager, (tab, position) -> {
            if (position == 0) {
                tab.setText("火力");
            } else if (position == 1) {
                tab.setText("口味");
            }
            tab.setCustomView(R.layout.tab_item);
            TextView tabItemText = tab.getCustomView().findViewById(R.id.tab_item_text);
            if (tabItemText != null) {
                tabItemText.setText(tab.getText());
            }
        }).attach();

        // 设置 Tab 选中监听器
        tablLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                // 设置选中时的背景
                tab.getCustomView().setBackgroundResource(R.drawable.button13); // 选中状态的背景
                // 更新所有 Tab 的背景
                for (int i = 0; i < tablLayout.getTabCount(); i++) {
                    TabLayout.Tab currentTab = tablLayout.getTabAt(i);
                    if (currentTab != null && currentTab.getCustomView() != null) {
                        if (currentTab == tab) {
                            currentTab.getCustomView().setBackgroundResource(R.drawable.button13); // 选中状态
                        } else {
                            currentTab.getCustomView().setBackgroundResource(R.drawable.touch2); // 未选中状态
                        }
                    }
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                // 未选中时的背景
                if (tab.getCustomView() != null) {
                    tab.getCustomView().setBackgroundResource(R.drawable.touch2);
                }
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                // 重新选中时的处理
                if (tab.getCustomView() != null) {
                    tab.getCustomView().setBackgroundResource(R.drawable.button13);
                }
            }
        });

        // 初始化时设置第一个 Tab 为选中状态
        TabLayout.Tab firstTab = tablLayout.getTabAt(0);
        if (firstTab != null && firstTab.getCustomView() != null) {
            firstTab.getCustomView().setBackgroundResource(R.drawable.button13);
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.adjust_food_back){//点击返回
            LoadingDialogUtil.showLoadingDialog(AdjustFoodActivity.this);
            finish();
        } else if (v.getId() == R.id.adjust_food_button1) {//点击保存
            // 获取当前的FirePowerFragmrnt实例
            FirePowerFragmrnt firePowerFragmrnt = (FirePowerFragmrnt) getSupportFragmentManager()
                    .findFragmentByTag("f0"); // "f0" 是ViewPager的第一个Fragment的标签
            if (firePowerFragmrnt != null) {
                List<FirePowerDate> firePowerDataList = firePowerFragmrnt.getCurrentData();
                onDataPass(firePowerDataList); // 调用接口方法传递数据
            }
            // 获取当前的SetTasteFragment实例
            SetTasteFragment setTasteFragment = (SetTasteFragment) getSupportFragmentManager()
                    .findFragmentByTag("f1"); // "f1" 是ViewPager的第二个Fragment的标签
            if (setTasteFragment != null) {
                List<TasteData> tasteDataList = setTasteFragment.getCurrentData();
                onTasteDataPass(tasteDataList); // 调用接口方法传递数据
            }
            Log.d("AdjustFoodActivity", "FirePower JSON Result showCustomDialog: " + savedJsonResult.toString());
            Log.d("AdjustFoodActivity", "Taste JSON Result showCustomDialog: " + savedTasteJsonResult.toString());
            select = 1;
            showCustomDialog();
        } else if (v.getId() == R.id.adjust_food_button2) {//点击立即炒菜
            // 获取当前的FirePowerFragmrnt实例
            FirePowerFragmrnt firePowerFragmrnt = (FirePowerFragmrnt) getSupportFragmentManager()
                    .findFragmentByTag("f0"); // "f0" 是ViewPager的第一个Fragment的标签
            if (firePowerFragmrnt != null) {
                List<FirePowerDate> firePowerDataList = firePowerFragmrnt.getCurrentData();
                onDataPass(firePowerDataList); // 调用接口方法传递数据
            }
            // 获取当前的SetTasteFragment实例
            SetTasteFragment setTasteFragment = (SetTasteFragment) getSupportFragmentManager()
                    .findFragmentByTag("f1"); // "f1" 是ViewPager的第二个Fragment的标签
            if (setTasteFragment != null) {
                List<TasteData> tasteDataList = setTasteFragment.getCurrentData();
                onTasteDataPass(tasteDataList); // 调用接口方法传递数据
            }
            Log.d("AdjustFoodActivity", "FirePower JSON Result showCustomDialog: " + savedJsonResult.toString());
            Log.d("AdjustFoodActivity", "Taste JSON Result showCustomDialog: " + savedTasteJsonResult.toString());
            select = 2;
            showCustomDialog();
        }
    }

    //获取火力
    @Override
    public void onDataPass(List<FirePowerDate> firePowerDataList) {
        // 将数据转换为JSONObject
        JSONObject jsonResult = convertToJSONObject(firePowerDataList);
        Log.d("AdjustFoodActivity","jsonResult: " + jsonResult);
        savedJsonResult = jsonResult; // 将转换后的JSONObject保存到全局变量
    }

    // 将List<FirePowerDate>转换为JSONObject
    private JSONObject convertToJSONObject(List<FirePowerDate> firePowerDataList) {
        JSONObject result = new JSONObject();
        JSONArray dataArray = new JSONArray();
        try {
            for (FirePowerDate item : firePowerDataList) {
                JSONObject dataItem = new JSONObject();
                dataItem.put("steep_index", item.getSteep_index());
                dataItem.put("title1", item.getTitle1());
                dataItem.put("title2", item.getTitle2());
                dataItem.put("value", item.getValue());
                dataItem.put("min_value", item.getMin_value());
                dataItem.put("max_value", item.getMax_value());
                dataItem.put("unit", item.getUnit());
                dataItem.put("step_value", item.getStep_value());
                dataItem.put("is_show",item.getIs_show());
                dataArray.put(dataItem);
            }
            result.put("success", true);
            result.put("data", dataArray);
        } catch (Exception e) {
            e.printStackTrace();
            try {
                result.put("success", false);
                result.put("error", e.getMessage());
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    //获取口味
    @Override
    public void onTasteDataPass(List<TasteData> tasteDataList) {
        // 将数据转换为JSONObject
        JSONObject jsonResult = convertTasteDataToJSONObject(tasteDataList);
        // 将转换后的JSONObject保存到全局变量
        savedTasteJsonResult = jsonResult;
    }

    // 将List<TasteData>转换为JSONObject
    private JSONObject convertTasteDataToJSONObject(List<TasteData> tasteDataList) {
        JSONObject result = new JSONObject();
        JSONArray dataArray = new JSONArray();
        try {
            for (TasteData item : tasteDataList) {
                JSONObject dataItem = new JSONObject();
                dataItem.put("steep_index", item.getSteepIndex());
                dataItem.put("title1", item.getTitle1());
                JSONArray steepDataArray = new JSONArray();
                for (TasteItem tasteItem : item.getSteepData()) {
                    JSONObject steepItem = new JSONObject();
                    steepItem.put("id", tasteItem.getId());
                    steepItem.put("title2", tasteItem.getTitle2());
                    steepItem.put("value", tasteItem.getValue());
                    steepItem.put("min_value", tasteItem.getMinValue());
                    steepItem.put("max_value", tasteItem.getMaxValue());
                    steepItem.put("unit", tasteItem.getUnit());
                    steepItem.put("step_value", tasteItem.getStepValue());
                    steepDataArray.put(steepItem);
                }
                dataItem.put("steep_data", steepDataArray);
                dataArray.put(dataItem);
            }
            result.put("success", true);
            result.put("data", dataArray);
        } catch (Exception e) {
            e.printStackTrace();
            try {
                result.put("success", false);
                result.put("error", e.getMessage());
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    private void showCustomDialog() {
//        AlertDialog.Builder builder = new AlertDialog.Builder(this);
//        LayoutInflater inflater = getLayoutInflater();
//        View dialogView = inflater.inflate(R.layout.adjust_food_dialog, null);
//        EditText editTextTag = dialogView.findViewById(R.id.adjust_food_dialog_edtext);
//        Button confirm = dialogView.findViewById(R.id.adjust_food_dialog_confirm);
//        ImageView cencal = dialogView.findViewById(R.id.food_details_cencle);
//        String name = ac.GetSQLData_Cooking_Config_NewName(vegetableId);
//        editTextTag.setText(name);
//        builder.setView(dialogView);
//        AlertDialog dialog = builder.create();
//        cencal.setOnClickListener(v -> dialog.dismiss());//点击取消
//        confirm.setOnClickListener(v -> {//点击确认
//            String tag = editTextTag.getText().toString().trim();
        String tag = "";
            String json_data = "";
//            if (!tag.isEmpty()) {
                if (savedTasteJsonResult == null || savedTasteJsonResult.length() == 0) {
                    if (savedJsonResult != null && savedJsonResult.length() > 0) {
                        json_data = ac.SaveSQLData_Cooking_Config_CopyNew(vegetableId, sid, savedJsonResult, null, tag);
                    } else {
                        json_data = ac.SaveSQLData_Cooking_Config_CopyNew(vegetableId, sid, null, null, tag);
                    }
                } else if (savedJsonResult == null || savedJsonResult.length() == 0) {
                    json_data = ac.SaveSQLData_Cooking_Config_CopyNew(vegetableId, sid, null, savedTasteJsonResult, tag);
                } else {
                    json_data = ac.SaveSQLData_Cooking_Config_CopyNew(vegetableId, sid, savedJsonResult, savedTasteJsonResult, tag);
                }
                Log.d("AdjustFoodActivity","savedJsonResult: " + savedJsonResult);
                Log.d("AdjustFoodActivity"," savedTasteJsonResult: " + savedTasteJsonResult);
                try {
                    // 解析JSON数据
                    JSONObject result = new JSONObject(json_data);
                    boolean isSuccess = result.getBoolean("success");
                    vegetableId = result.getInt("vegetable_id");
                    sid = result.getInt("spec_id");
                    Log.d("AdjustFoodActivity","vegetable_id: " + vegetableId + " spec_id: " + sid);
                    if (isSuccess) {
//                        Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
                        ToastUtils.show(this, "保存成功");
                        if (select == 1){//保存菜谱
//                            dialog.dismiss();
                            CustomBottomSheetDialogFragment dialogFragment = new CustomBottomSheetDialogFragment();
                            dialogFragment.setVegetableId(String.valueOf(vegetableId));
                            dialogFragment.show(getSupportFragmentManager(), "CustomBottomSheetDialog");
                        } else if (select == 2) {//立即烹饪
                            LoadingDialogUtil.showLoadingDialog(AdjustFoodActivity.this);
                            Intent intent = new Intent(this, CookActivity.class);
                            intent.putExtra("vegetableId", String.valueOf(vegetableId));
                            intent.putExtra("sid", String.valueOf(sid));
                            intent.putExtra("quantity",copiesQty);
                            startActivity(intent);
//                            dialog.dismiss();
                            finish();
                        }
                    } else {
                        String errorDesc = result.optString("desc", "保存失败");
//                        Toast.makeText(this, errorDesc, Toast.LENGTH_SHORT).show();
                        ToastUtils.show(this, errorDesc);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
//                    Toast.makeText(this, "数据解析失败", Toast.LENGTH_SHORT).show();
                    ToastUtils.show(this, "数据解析失败");
                }
            }
//            else {
//                Toast.makeText(this, "请输入标签", Toast.LENGTH_SHORT).show();
//            }
//        });

//        dialog.show();
//        // 关键代码：设置窗口背景透明
//        if (dialog.getWindow() != null) {
//            dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
//        }
//        // 关键代码：设置点击外部不可取消
//        dialog.setCanceledOnTouchOutside(false);
//    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if ("ACTION_CLOSE_LOADING_DIALOG".equals(intent.getAction())) {
                LoadingDialogUtil.closeLoadingDialog();
            }
        }
    };

    @Override
    protected void onStart() {
        super.onStart();
        LocalBroadcastManager.getInstance(this).registerReceiver(receiver, new IntentFilter("ACTION_CLOSE_LOADING_DIALOG"));
    }

    @Override
    protected void onStop() {
        super.onStop();
        LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 在界面渲染完成后发送广播关闭弹窗
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                ((ApplicationClass) getApplication()).sendBroadcast("ACTION_CLOSE_LOADING_DIALOG");
            }
        });
    }
}